package com.servlet;

import com.dao.impl.AdminDaoImpl;
import com.entity.Users;
import com.service.AdminService;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.Cookie;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.io.IOException;
import java.util.Objects;

import static com.util.Constant.*;

@WebServlet(name = "AdminLoginServlet",value = "/adminLogin")
public class AdminLoginServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.getRequestDispatcher("/admin.jsp").forward(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String username = req.getParameter(USERNAME);
        String password = req.getParameter(PASSWORD);
        String remember = req.getParameter(REMEMBER);
        AdminService adminService = new AdminService();
        try {
            Users user = adminService.login(username, password);
            if(Objects.nonNull(user)){
                req.getSession().setAttribute("username",username);

                if("on".equals(remember)){
                    Cookie cookie = new Cookie(username, username);
                    cookie.setPath("/");
                    cookie.setMaxAge(60 * 60 * 24 *3);
                    resp.addCookie(cookie);
                }

                req.setAttribute("user",user);
                req.getRequestDispatcher("/admin/index1.jsp").forward(req, resp);
            }else {
                req.setAttribute("errors","账号名错误或者密码错误，请重新登录");
                req.getRequestDispatcher("/admin.jsp").forward(req, resp);
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}
